﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using MicropleSoft.WmsServiceLibrary.Common;

namespace MicropleSoft.WmsServiceLibrary.BaseDataService
{
    public class BaseDataConfigReader : IBaseDataConfigReader
    {
      
        public  List<BaseDataConfigEntity> Read()
        {
            return Read("BaseData.Config");
        }

        public List<BaseDataConfigEntity> Read(string file)
        {
            var list = new List<BaseDataConfigEntity>();
            string fileName = ApplicationPath.GetApplicationPath() + "\\"+ file;
            var root = XElement.Load(fileName);

            var dataList = from element in root.Descendants("Data")
                       select element;
            foreach(XElement xElement in dataList)
            {
                var elements = from xe in xElement.Elements() 
                        select xe;
                var entity = new BaseDataConfigEntity();
                entity.Key = xElement.Attribute("Key").Value;
                entity.Sql = xElement.Attribute("Sql").Value;
                entity.LookUpViewHeaderList = new List<LookUpViewHeader>();

                foreach (XElement xNode in elements)
                {
                    var header = new LookUpViewHeader();
                    if (xNode.Attribute("Field") != null)
                    {
                        header.Field = xNode.Attribute("Field").Value;
                    }
                    else
                    {
                        throw new Exception(file + "的属性Field不能为空！");
                    }
                    
                    header.Caption = (String)xNode.Attribute("Caption").Value;
                    header.Width = Int32.Parse(xNode.Attribute("Width").Value);
                    header.IsEditValue = Boolean.Parse(xNode.Attribute("IsEditValue").Value);
                    header.IsDisplayValue = Boolean.Parse(xNode.Attribute("IsDisplayValue").Value);

                    if (xNode.Attribute("IsVisual") != null)
                    {
                        header.IsVisual = Boolean.Parse(xNode.Attribute("IsVisual").Value);
                    }
                    else
                    {
                        header.IsVisual = true;
                    }

                    entity.LookUpViewHeaderList .Add(header);
                }

                list.Add(entity);
            }

            return list;
        }
    }
}
